import roleServices from '@/services/role';
import userServices from '@/services/user';
import {PageContainer, ProDescriptionsActionType, ProList,} from '@ant-design/pro-components';
import type {MenuProps} from 'antd';
import {Button, Dropdown, message, Space} from 'antd';
import {DownOutlined, UserOutlined} from '@ant-design/icons';
import {useLocation, useParams} from 'react-router-dom';
import type {Key} from 'react';
import React, {useEffect, useRef, useState} from 'react';
import AddUserRoleForm from '../components/AddUserRoleForm';

const {roles} = roleServices.RoleController;
const {assignRole,findUserRoles, cancelRole} = userServices.UserController;


/**
 * 分配角色
 * @param fields
 */
const addUserRole = async (fields: API.RoleUserSetting) => {
    const hide = message.loading('正在添加');
    try {
        await assignRole({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

/**
 * 取消用户的角色
 * @param fields
 */
const deleteUserRole = async (fields: API.RoleUserSetting) => {
    const hide = message.loading('正在取消');
    try {
        await cancelRole({...fields});
        hide();
        message.success('取消成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};


const TableList: React.FC<unknown> = () => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const [addRoleVisible, handleRoleVisible] = useState<boolean>(false);
    // roles
    const [roleItems, setRoleItems] = useState<Array<{ key: string; label: string; icon: React.ReactElement }>>([]);

    const rowSelection = {
        selectedRowKeys,
        onChange: (keys: Key[]) => setSelectedRowKeys(keys),
    };
    const actionRef = useRef<ProDescriptionsActionType>();
    const {userId} = useParams();
    // 确保userId不是undefined
    const userIdForRequest = userId !== undefined ? userId : '';

    const location = useLocation();
    const searchParams = new URLSearchParams(location.search);
    const name = searchParams.get('userName');


    // 给用户添加角色 api
    const handleAddRoleClick: MenuProps['onClick'] = async (value) => {
        console.log('click', value);

        const add: API.RoleUserSetting = {
            userId: userIdForRequest,
            roleCode: value.key
        };
        console.log("add: " + JSON.stringify(add))
        const success = await addUserRole(add);
        if (success) {
            handleRoleVisible(false);
            if (actionRef.current) {
                actionRef.current.reload();
            }
        }
    };


    // 异步加载角色数据
    useEffect(() => {
        roles().then((data) => {
            const items = data.data?.map((item: { code: any; name: any; }) => ({
                key: item.code,
                label: item.name,
                icon: <UserOutlined/>,
            }));
            setRoleItems(items || []);
            // setRoleLoading(false);
        })
    }, []); // 空数组确保仅在组件挂载时执行


    const menuProps = {
        items: roleItems,
        onClick: handleAddRoleClick,
    };

    const fetchData = async (params: any): Promise<{ data: API.RoleVO[] }> => {
        const response = await findUserRoles({
            userId: userIdForRequest,
            ...params,
        });
        return {
            data: Array.isArray(response.data) ? response.data.filter(item => item !== null) as API.RoleVO[] : [],
        };
    };

    return (
        <PageContainer
            header={{
                title: `${name}拥有的角色`,
            }}
        >
            <ProList<API.RoleVO>
                rowKey="title"
                actionRef={actionRef}
                // headerTitle={`${name}拥有的角色`}
                toolBarRender={() => {
                    return [
                        <Button
                            key="1"
                            type="primary"
                            onClick={() => handleRoleVisible(true)}
                        >
                            新增
                        </Button>,
                    ];
                }}
                metas={{
                    title: {
                        dataIndex: 'name',
                        title: '角色名称',
                    },
                    description: {
                        dataIndex: 'code', // 显示字段
                        title: '角色编码',
                    },
                    avatar: {
                        dataIndex: 'iamge',
                        render: (text) => (
                            <img
                                src="https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg"
                                alt="avatar" style={{width: '32px', height: '32px', borderRadius: '50%'}}/>
                        ),
                        editable: false,
                    },
                    actions: {
                        render: (text, row) => [
                            <a key="delete" onClick={async () => {
                                const success = await deleteUserRole({
                                    "userId": userIdForRequest,
                                    "roleCode": row.code
                                });
                                if (success) {
                                    actionRef.current?.reloadAndRest?.();
                                }
                            }}>删除</a>,
                        ],
                    },
                }}
                request={fetchData}
                rowSelection={rowSelection}
            />


            <AddUserRoleForm
                onCancel={() => handleRoleVisible(false)}
                modalVisible={addRoleVisible}
            >
                <Dropdown
                    menu={menuProps}
                >
                    <Button icon={<UserOutlined/>}>
                        <Space>
                            请选择需要添加的角色
                            <DownOutlined/>
                        </Space>
                    </Button>
                </Dropdown>
            </AddUserRoleForm>
        </PageContainer>
    );

};

export default TableList;
